from random import randint

def joueur_o(P4, num_joueur):
    
    for i in range(len(P4)):         #blocage horizontal de droite a gauche
            for j in range(len(P4[0])):
                if P4[i][j] == P4[i][j-1] and P4[i][j] != 0 and j-2 >=0 and P4[i][j-2] == 0:
                    return j-2
    
    for i in range(len(P4)):         #blocage horizontal de gauche a droite
            for j in range(len(P4[0])):
                if P4[i][j] == P4[i][j-1] and P4[i][j] != 0 and j+1 <= len(P4):
                    if P4[i][j+1] == 0:
                        return j+1

    for i in range(len(P4)):         #blocage colonne
            for j in range(len(P4[0])):
                if P4[i][j] == P4[i-1][j] and P4[i][j] != 0 and P4[i-2][j] == 0:
                    return j
                
    for i in range(len(P4)):         #blocage diagonal a partir de la gauche
            for j in range(len(P4[0])):
                if P4[i][j] == P4[i-1][j-1] and P4[i][j] != 0 and (j-2) >= 0 and (i-1) != 0 and j+1 <= len(P4):
                    return j-2
                
    for i in range(len(P4)):         #blocage diagonal a partir de la droite
            for j in range(len(P4[0])):
                if P4[i][j] != 0 and (j-2) >= 0 and (i-1) != 0 and j+2 <= (len(P4[0])-1):
                    if P4[i][j] == P4[i-1][j+1]:
                        return j+2
                    
    for i in range(len(P4)):        #debut partie, commence des petites colonnes
        for j in range(len(P4[0])): # et lignes
            if P4[i][j] == num_joueur and P4[i-1][j] == 0 and i-1 >= 0:
                return j
            elif P4[i][j] == num_joueur and j+1 <= (len(P4[0])-1) and P4[i][j+1] == 0:
                return j+1
            elif P4[i][j] == num_joueur and j-1 >= 0 and P4[i][j-1] == 0:
                return j-1
            
    milieu = 0          #premier joueur
    for e in P4[-1] :
        if e != 0:
            milieu += 1
    if milieu == 0:
        return len(P4[-1])//2
                    
    return randint(0,6)